import React, {useContext, useEffect, useState} from 'react';
import {Alert, Dimensions, FlatList, ImageBackground, Platform, TouchableOpacity, View} from 'react-native';
import {Divider, ListItem, Text} from 'react-native-elements';

import LocaleContext from '../libs/locale';
import WalletContext from '../libs/wallet';
import {formartMoney, timeFormat} from '../libs/helpers';
import {
  getBalances,
  getHotTokens, getTxInfo,
  getTxs,
  getTxStatus,
  retranTokenTransfer,
  retranTransfer,
  transfer
} from '../libs/nodes';
import {addTx, getTxs as getPendingTxs, getTxs2, popTx, saveTX} from '../libs/pendingTxs';
import {useFocusEffect, useNavigation} from '@react-navigation/native';

import tranout from '../assets/tranout.png';
import tranin from '../assets/tranin.png';
import logo from '../assets/logo.png';
import {constansts} from '../libs/constansts';
import AsyncStorage from '@react-native-async-storage/async-storage';
// import wallet from '../libs/wallet';

const {width,height} = Dimensions.get("window");
console.log("屏幕="+width+" "+height);



const Txs = ({ navigation, route }: any) => {
  const locale: any = useContext(LocaleContext);
  const [lang, setLang] = useState("zh");
  const [isAll, setIsAll] = useState(route?.params?.kind !== 'Pending');
  const [money, setMoney] = useState("");
  const wallet: any = useContext(WalletContext);
  const [refresh, setRefresh] = useState(true);
  const [SATprice, setSATPrice] = useState("0.00");

  const work = async () => {
    if (!refresh) {
      return;
    }
    setRefresh(false);
    const balances = await getBalances(wallet.address);
    constansts.SATcount=balances.SAT;
    await AsyncStorage.setItem("Asset_SATcount",(balances.SAT).toString())
    setMoney(balances.SAT);
    getSATPrice();
  }

  const refreshMoney=async ()=>{
    const balances = await getBalances(wallet.address);
    constansts.SATcount=balances.SAT;
    setMoney(balances.SAT);
    getSATPrice();
  }
//定时器
  useEffect(()=>{
    const t=setInterval(refreshMoney,5000);

    return ()=> {
      clearInterval(t);
    }
  },[])
//初始化函数
  useEffect(()=>{
    work();
  },[refresh]);

  const getSATPrice = async () => {
    // const ht = await getHotTokens();
    // const p = ht.dict;
    // const price = parseFloat(p.satprice);
    // var MySat = price * parseFloat(constansts.SATcount);
    // constansts.SATprice = price;
    // var MySatMoney = formartMoney(MySat.toString(),4);
    // console.log("金额="+MySatMoney+"   "+constansts.SATcount+"    "+new Date().getSeconds())
    // setSATPrice(MySatMoney);

    const lang = await AsyncStorage.getItem('@lang');
    setLang(lang as any);
    const ht = await getHotTokens();
    const p = ht.dict;
    const price = parseFloat(p.satprice);
    const usdtPrice =parseFloat(p.usdtprice);
    constansts.SATprice = price;
    constansts.USDTprice=usdtPrice;
    var MySat = 0;
    if(lang=='zh')
      MySat = price * parseFloat(constansts.SATcount);
    else
      MySat = usdtPrice * parseFloat(constansts.SATcount);
    var MySatMoney = formartMoney(MySat.toString(),4);
    console.log("金额="+MySatMoney+"   "+constansts.SATcount+"    "+new Date().getSeconds())
    setSATPrice(MySatMoney);
  };

  return (
    <View style={{ flex: 1 }}>
       <View>
      <View style={{ alignItems:'center',marginTop: Platform.OS == 'ios' ? 40 : 0}}>
      <ImageBackground source = {logo} style={{marginTop:60,width:40,height:40,}} />
      <Text style={ { fontSize:30,fontWeight:'bold',color:"#333750",marginTop:0}}> { formartMoney(money, 4) }</Text>
        {
          lang=="zh"?
          <Text style={ { fontSize:20,fontWeight:'100',color:"#9DA1AC",marginTop:8}}> {"≈¥"+SATprice }</Text>
            :
          <Text style={ { fontSize:20,fontWeight:'100',color:"#9DA1AC",marginTop:8}}> {"≈$"+SATprice }</Text>
        }
      </View>
      </View>
      <View>
        <View style={{
          flexDirection: 'row',
          justifyContent: 'space-around',
          marginTop: 20
        }}>
          <View style={{ alignItems: 'center' }}>
            <Text
              style={{
                fontSize: 18,
                fontWeight: 'bold',
                paddingBottom: 10,
                ...isAll ? { color: '#7367E3' } : {}
              }}
              onPress={() => setIsAll(true)}
            >{locale?._('Assets.txs.all')}</Text>
            {
              isAll ?
                <Divider style={{
                  borderColor: '#7367E3',
                  borderWidth: 1.2,
                  width: 30
                }} />
                : <></>
            }
          </View>
          <View style={{ alignItems: 'center' }}>
            <Text
              style={{
                fontSize: 18,
                fontWeight: 'bold',
                paddingBottom: 10,
                ...!isAll ? { color: '#48C1AD' } : {}
              }}
              onPress={() => setIsAll(false)}
            >{locale?._('Assets.txs.pending')}</Text>
            {
              !isAll ?
                <Divider style={{
                  borderColor: '#48C1AD',
                  borderWidth: 1.2,
                  width: 30
                }} />
                : <></>
            }
          </View>
        </View>
        <Divider style={{ marginLeft: 10, marginRight: 10 }} />
      </View>

      {isAll ? <History  /> : <Pending />}
      {/*navigation={navigation}*/}
    </View>
  );
};

const Pending = ({}:any) => {
  const locale: any = useContext(LocaleContext);
  const [txs, setTxs] = useState<any>([]);
  const [refresh, setRefresh] = useState(true);
  const navigation = useNavigation();
  const wallet: any = useContext(WalletContext);

  const reTran=async (item:any,index:number)=>{

      console.log("index=" + index);
      var tx;
      if (item.type == "transfer")
        tx = await retranTransfer(item.hash, wallet.address, item.addressOut,
            item.amount, item.remarks == "errortransferbug" ? "item.remarks" : item.remarks, item.nonce, item.timestamp, item.sign);
      else {
        tx = await retranTokenTransfer(item.hash, wallet.address, item.addressOut,
            item.data, item.remarks == "errortransferbug" ? "item.remarks" : item.remarks, item.receiver, item.nonce, item.timestamp, item.sign);
      }
      if (tx.reason!=1)
      {
          console.log("重发失败")
          console.log("retran false reason:"+tx.reason);
          Alert.alert('', locale._('Assets.send.sendFail'));
      }
      else
      {
        console.log("重发成功")
        await popTx(item.hash);
        await addTx(tx);
        Alert.alert('', locale._('Assets.send.sendSuccess'));
        setRefresh(true);
      }



  }

  var active=1;
  var flag=false;

  //定时器处理交易
  const inwork = async()=>{
    if(active==0)
    {
      console.log(active);
      return;
    }
    active=0;
    var txx = await getTxs2();
    await txx.map(async (tx:any,index:number)=>{
      //获取交易状态接口 //状态 -1网络问题 0丢失 1完成 2发送中 3失败 -2没有这个接口
      var txStatus = await getTxStatus(tx.hash);
      if(txStatus == -1 || txStatus == 2)
      {
        return;
      }
      else if (txStatus === -2)
      {
        let res = await getTxInfo(tx.hash);
        if(res.height === 0)
        {
          txx[index].height=0;
          await saveTX(txx);
        }
        else if (res.height > 0)
        {
          await popTx(tx.hash);
          return;
        }
        else if ( res === false && (((new Date().getTime())-tx.trantime)>(2*60*1000)) )
        {
          txx[index].height=-2;
          await saveTX(txx);
          return;
        }
      }
      else if(txStatus == 0)
      {
        txx[index].height=-2;
        await saveTX(txx);
        return;
      }
      else if(txStatus == 1)
      {
        await popTx(tx.hash);
        return;
      }
      else if(txStatus == 3)
      {
        txx[index].height=0;
        await saveTX(txx);
      }
    })

    try {
      const txs = await getPendingTxs();
      const txsdata=txs.reverse();
      if(flag)
      {
        return ;
      }
      setTxs(txsdata);
    } catch (e) {
      console.log('getPendingTxs inwork:', e);
    }
    active=1;
  }
  //定时器
  useEffect(()=>{
    const t=setInterval(async ()=>{
      const txs = await getPendingTxs();
      const txsdata=txs.reverse();
      setTxs(txsdata);
    },5000);
    return ()=>{
      flag=true;
      clearInterval(t);}
  },[])
  //初始化函数
  useEffect(() => {
    const work = async () => {
      if (!refresh) {
        return;
      }
      setRefresh(false);
      //await inwork();
      const balances = await getBalances(wallet.address);
      constansts.SATcount = balances.SAT;
      await AsyncStorage.setItem("Asset_SATcount",(balances.SAT).toString())
      try {
        const txs = await getPendingTxs();
        const txsdata=txs.reverse();
        if(flag)
        {
          return ;
        }
        setTxs(txsdata);
      } catch (e) {
        console.log('getPendingTxs:', e);
      }
    };
    work();

  }, [refresh]);
  //页面转换执行函数
  useFocusEffect(
      React.useCallback(() => {
        const work = async () => {
          const txs = await getPendingTxs();
          const txsdata = txs.reverse();
          setTxs(txsdata);
        }
        work();
      }, [])
  );

  const retrievedMoney = (remarks:any)=>{
    try{
      const res = remarks.split("：");
      return res[1];
    } catch (e) {
      return "0";
    }
  }
  const delInfo = async (item: any) => {
    // console.log(item.height);
    var txx = await getTxs2();
    // console.log(JSON.stringify(txx))
    // console.log(JSON.stringify(item))
    let index = txx.findIndex((res: any) => res.sign === item.sign);
    // console.log(index)
    txx.splice(index,1);
    await saveTX(txx);
    setTxs(txx.reverse());
    return;
  }
  const clearAllPending = async () => {
    let txx: any[] = [];
    await saveTX(txx);
    setTxs(txx);
    return;
  }

  const renderItem = ({ item, index }: any) => (
    <View >
      <ListItem
        onPress={() =>{
        (navigation as any).push('TxDetails', { tx: item });
        }}
        onLongPress={()=>{
          if(item.height== -1)
          {
            return;
          }
          Alert.alert('', locale._("Txs.AlertDel"), [
            {
              text: locale?._('clearAll'),
              onPress: async () => {
                await delInfo(item)
              }
            },{
            text: locale?._('cancel'),
            onPress: () => console.log("Cancel Pressed"),
            style: "cancel"
          }, {
            text: locale?._('ok'),
            onPress: async () => {
              await delInfo(item)
            }
          }]);

        }}
        style={{ }}>
          <View>
            <Text></Text>
          </View>
          {
            <ImageBackground source = {tranout} style={{marginTop: -7, width: 20, height: 20}}/>
          }
        <View >
          <Text
            style={{ color: 'black', fontSize: 15 ,marginBottom:5}}
          > {item.hash.slice(0, 6)}...{item.hash.slice(-6)}</Text>
          <Text style={{ height:12,fontSize: 10, color: 'lightgrey',marginTop:0,paddingLeft:5 ,paddingBottom:0}}>{timeFormat(item.trantime)}</Text>
        </View>
        <View style={{ flex:1 }} />
        <View style={{ alignItems: 'flex-end' }}>
        {
          item.addressIn !== wallet.address
              ?
              <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>+{formartMoney(item.amount, 4)}</Text>
              :
              (item.data.indexOf("addLiquidity")!==-1?
                      <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>-{formartMoney(item.data.match(/\"(.*?)\"/)[1],4)}</Text>
                      :
                      (
                          item.data.indexOf("retrieved")!==-1?
                              <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>+{formartMoney(retrievedMoney(item.remarks),4)}</Text>
                              :
                              <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>-{formartMoney(item.amount, 4)}</Text>

                      )
              )
          // <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>-{formartMoney(item.amount, 4)}</Text>
        }

        {
           item.height==-2 ?
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
           <TouchableOpacity
             onPress={() => reTran(item,index)}
             style={{ borderWidth:1,borderColor:"#F1F2F4",backgroundColor: '#FBFCFE', paddingHorizontal: 6, borderRadius: 8, marginRight: 10,width:55,height:20,alignItems:"center",justifyContent:"center" }}
           >
             <Text style={{ fontSize: 12, color: '#1287D8', lineHeight: 18 }}>{locale?._('Assets.txs.resend')}</Text>
           </TouchableOpacity>
           <Text style={{ color: '#F15F5FFF' }}>{locale._('Assets.txs.lose')}</Text>
         </View>
         :
         (
             item.height==0?
             <Text style={{ height:13,color: ('#F15F5FFF') ,fontSize:10,paddingBottom:0}}>{locale._('Assets.txs.failure')}</Text>
             :
             <Text style={{ height:13,color: ('#0BBED5') ,fontSize:10,paddingBottom:0}}>{locale._('Assets.txs.waiting')}</Text>
         )
        }
        </View>
    </ListItem>
      <View style={{ height: 0, borderTopWidth: 0.5, borderColor: "#DCD4D4",opacity: 0.7, margin: 1,marginLeft:80 }} />
    </View>
  );

  return (
    <FlatList
      renderItem={renderItem}
      data={txs}
      keyExtractor={item => item.hash}
      style={{ marginBottom: 60 }}
      ListEmptyComponent={
        <Text style={{
          marginTop: 160,
          fontSize: 20,
          textAlign: 'center',
          color: 'grey'
        }}>{locale._('noContent')}</Text>
      }
      refreshing={false}
      onRefresh={() => setRefresh(true)}
    />
  );
};

const History = ({ }: any) => {
  const locale: any = useContext(LocaleContext);
  const wallet: any = useContext(WalletContext);

  const [loadMore, setLoadMore] = useState(true);
  const [lastIndex, setLastIndex] = useState(0);
  const [lastFetched, setLastFetched] = useState(0);
  const [data, setData] = useState<any>([]);
  const navigation=useNavigation();
  var flag = false;


  useEffect(() => {
    var work = async () => {
      if (!loadMore) {
        return;
      }
      let li = lastIndex;
      let lf = lastFetched;
      try {
        if (lastFetched === 12) {
          li += 1;
          lf = 0;
          setLastIndex(li);
          setLastFetched(lf);
        }

        constansts.transData = await getTxs(wallet.address, li);
        if (flag) {
          return;
        }
        setLastFetched(constansts.transData.length);
        constansts.transData.splice(0, lf);
        setData(data.concat(constansts.transData));
        setLoadMore(false);
      } catch (e) {
        console.log('getTxs:', e);
      }
    };
    work();

  }, [loadMore]);

  useEffect(()=>{
    return ()=> {

      // setLoadMore = ()=>{
      //   return;
      // };
      //
      // setLastIndex = ()=>{
      //   return;
      // };
      // setLastFetched = ()=>{
      //   return;
      // };
      //
      // setData = ()=>{
      //   return;
      // };

      flag = true;
    }
  },[])

  const retrievedMoney = (remarks:any)=>{
    try{
      const res = remarks.split("：");
      return res[1];
    }catch (e) {
      return "0";
    }

  }

  const renderItem = ({ item, index }: any) => (
    <View >
      <ListItem
        onPress={() =>{
          (navigation as any).push('TxDetails', { tx: item });
        }}
        style={{ }}>
          {
             item.addressIn === wallet.address
             ?
             <ImageBackground source = {tranout} style={{marginTop:-7,width:20,height:20}}></ImageBackground>
             :
             <ImageBackground source = {tranin} style={{marginTop:-7,width:20,height:20}}></ImageBackground>
          }
        <View style={{marginLeft:-5}}>
          <Text
            style={{ color: 'black', fontSize: 15 ,marginBottom:5}}
          > {item.type=="transfer"?
              (item.addressIn === wallet.address
                      ?
                      item.addressOut.slice(0, 6) + "..." + item.addressOut.slice(-6)
                      :
                      item.addressIn.slice(0, 6) + "..." + item.addressIn.slice(-6)
              )
              :
              (((item.type=="contract" && item.addressOut=="") ?
                  locale?._('Assets.tx.contractRelease')
                  :
                  (item.type=="contract" && (item.data.indexOf("transfer")==-1))?
                      locale?._('Assets.tx.contractCall')
                      :
                      (item.addressIn === wallet.address
                              ?
                              item.addressOut.slice(0, 6) + "..." + item.addressOut.slice(-6)
                              :
                              item.addressIn.slice(0, 6) + "..." + item.addressIn.slice(-6)
                      )))}</Text>
          <Text style={{ height:12,fontSize: 10, color: 'lightgrey',marginTop:0,paddingLeft:5 ,paddingBottom:0}}>{timeFormat(item.timestamp)}</Text>
        </View>
        <View style={{ flex:1 }} />
        <View style={{ alignItems: 'flex-end' ,marginRight:6}}>
        {
          item.addressIn !== wallet.address
            ?
            <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>+{formartMoney(item.amount, 4)}</Text>
            :
            (item.data.indexOf("addLiquidity")!==-1?
              <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>-{formartMoney(item.data.match(/\"(.*?)\"/)[1],4)}</Text>
                    :
                (
                  item.data.indexOf("retrieved")!==-1?
                  <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>+{formartMoney(retrievedMoney(item.remarks),4)}</Text>
                        :
                  <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>-{formartMoney(item.amount, 4)}</Text>

                )
            )
        }
        {
            <Text style={{ height:12,color:(item.addressIn === wallet.address?'#0BBED5':"#7367E3") ,fontSize:10,paddingBottom:0}}>{locale._('Assets.txs.success')}</Text>
        }
        </View>
    </ListItem>
      <View style={{ height: 0, borderTopWidth: 0.5, borderColor: "#DCD4D4",opacity: 0.7, margin: 1,marginLeft:60,marginRight:16 }} />
    </View>
  );

  return (
    <FlatList
      renderItem={renderItem}
      data={data}
      keyExtractor={item => item.hash}
      onEndReached={() => {
        console.log("加载更多？");
        setLoadMore(true);
      }}
      refreshing={false}
      onRefresh={() => {
        setLastIndex(0);
        setLastFetched(0);
        setData([]);
        setLoadMore(true);
      }}
      style={{ marginBottom: 0 }}
      ListEmptyComponent={
        <Text style={{
          marginTop: 160,
          fontSize: 20,
          textAlign: 'center',
          color: 'grey',
        }}>{locale._('noContent')}</Text>
      }/>
  );
};

export default Txs;
